<?php

namespace Apps\News\Models;

use App\Models\ComModel;

class NewsModel extends ComModel
{

    public $tablename;
    private $categorys;

    public function __construct(...$param)
    {
        parent::__construct();
        $this->table = 'news';
    }
    //新增和编辑全部数据时验证
    private function _validate($data, $id = 0)
    {
        if (!$data) {
            return mok_rt(1, '分类名称必须填写');
        }
        foreach ($data as $k => $v) {
            if ($v) {
                $data[$k] = mok_clean_xss($v);
            }
        }
        if (!$data['title']) {
            return mok_rt(1, '标题必须填写');
        } elseif (!$data['content']) {
            return mok_rt(1, '详情内容必须填写');
        } elseif ($data['status'] == 2 && !$data['admin_note']) {
            return mok_rt(1, '请填写拒绝说明');
        } elseif (!$data['catid']) {
            return mok_rt(1, '请选择分类');
        }

        $flag = $this->field_exitsts($this->table, 'title', $data['title'], $id);
        if ($flag) {
            return mok_rt(1, '公告通知标题已存在');
        }
        $flag = $this->db->table($this->table . '_cat')->where('id', (int) $data['catid'])->countAllResults();
        if (!$flag) {
            return mok_rt(1, '请选择分类');
        }
        return mok_rt(0, 'OK', $data);
    }

    public function add($data)
    {
        $rt = $this->_validate($data);
        if ($rt['code']) {
            return $rt;
        }

        $idata1 = [
            'title' => $data['title'],
            'catid' => intval($data['catid']),
            'inputtime' => isset($data['inputtime']) && $data['inputtime'] ? strtotime($data['inputtime']) : time(),
            'updatetime' => $data['updatetime'] ? strtotime($data['updatetime']) : time(),
            'keywords' => $data['keywords'] ? mok_meta_keyword($data['keywords']) : '',
            'hits' => $data['hits'] ? intval($data['hits']) : 0,
            'description' => (isset($data['description']) && $data['description']) ? $data['description'] : trim(mok_strcut(mok_clearhtml($data['content']), 200)),
            'thumb' => isset($data['thumb']) ? intval($data['thumb']) : 0,
            'status' => isset($data['status']) ? intval($data['status']) : 0,
            'displayorder' => 0,
        ];
        $this->db->table($this->table)->insert($idata1);
        $id = $this->db->insertID();
        if ($id) {
            //附件归属
            if (isset($data['thumb']) && $data['thumb']) {
                $related = $this->table . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['status']))->update(['related' => $related]);
            }
            $idata2 = [
                'id' => $id,
                'catid' => intval($data['catid']),
                'content' => $data['content'],
            ];
            $flag = $this->db->table($this->table . '_data')->replace($idata2);
            if (!$flag) {
                return mok_rt(1, '操作失败', array_merge($idata1, $idata2));
            }
            return mok_rt(0, '操作成功', $id);
        }
        return mok_rt(1, '操作失败', $idata1);
    }

    public function edit($id, $data)
    {
        if (!$id) {
            return mok_rt(1, '参数错误');
        }
        $rt = $this->_validate($data, $id);
        if ($rt['code']) {
            return $rt;
        }

        $idata1 = [
            'title' => $data['title'],
            'catid' => intval($data['catid']),
            'inputtime' => (isset($data['inputtime']) && $data['inputtime']) ? strtotime($data['inputtime']) : time(),
            'updatetime' => isset($data['updatetime']) ? strtotime($data['updatetime']) : time(),
            'keywords' => isset($data['keywords']) ? mok_meta_keyword($data['keywords']) : '',
            'hits' => isset($data['hits']) ? intval($data['hits']) : 0,
            'description' => (isset($data['description']) && $data['description']) ? $data['description'] : trim(mok_strcut(mok_clearhtml($data['content']), 200)),
            'thumb' => isset($data['thumb']) ? intval($data['thumb']) : 0,
            'status' => isset($data['status']) ? intval($data['status']) : 0,
        ];

        $flag = $this->db->table($this->table)->where('id', $id)->update($idata1);

        if ($flag) {
            //附件归属
            if (isset($data['thumb']) && $data['thumb']) {
                $related = $this->table . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['status']))->update(['related' => $related]);
            }
            $idata2 = [
                'id' => $id,
                'catid' => intval($data['catid']),
                'content' => $data['content'],
            ];
            $flag = $this->db->table($this->table . '_data')->where('id', $id)->replace($idata2);
            if (!$flag) {
                return mok_rt(1, '操作失败', array_merge($idata1, $idata2));
            }
            return mok_rt(0, '操作成功', $id);
        }
        return mok_rt(1, '操作失败', array_merge($idata1, $idata2));
    }

    public function get($id)
    {
        if (!$id) {
            return mok_rt(1, '参数错误');
        }
        $row = $this->db->table($this->table)->join($this->table . '_data', $this->table . '_data.id = ' . $this->table . '.id')->where($this->table . '.id', $id)->get()->getRowArray();
        if (!$row) {
            return mok_rt(1, '数据不存在', []);
        }
        if ($row['thumb']) {
            $row['thumb_info'] = $this->db->table('attachment')->select('filename,attachment')->where('id', intval($row['thumb']))->get()->getRowArray();
        }
        if ($row) {
            $row['inputtime_date'] = date('Y-m-d H:i', $row['inputtime']);
            $row['updatetime_date'] = date('Y-m-d H:i', $row['updatetime']);
        }
        return $row;
    }

    public function del($id)
    {
        if (!$id) {
            return mok_rt(1, '参数错误');
        }
        // $row = $this->db->table($this->table)->select('id,title')->where('id', $id)->get()->getRowArray();
        $row = $this->db->table($this->table)->join($this->table . '_data', $this->table . '_data.id = ' . $this->table . '.id')->where($this->table . '.id', $id)->get()->getRowArray();
        if (!$row) {
            return mok_rt(1, '数据不存在', []);
        }
        $this->db->table($this->table)->where('id', $id)->delete();
        $this->db->table($this->table . '_data')->where('id', $id)->delete();
        return mok_rt(0, 'OK');
    }

    // 分页
    public function limit_page($page = 0, $size = 10, $total = 0, $param = [])
    {

        $page = max(1, (int) $page);
        $total = (int) $total;

        unset($param['page']);
        if (isset($param['keyword']) && $param['keyword']) {
            $param['keyword'] = trim(urldecode($param['keyword']));
        }

        if ($size > 0 && !$total) {
            $select = $this->db->table($this->table)->select('count(*) as total');
            $param = $this->_limit_page_where($select, $param);
            $query = $select->get();
            if (!$query) {
                log_message('error', '数据查询失败：' . $this->table);
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->table);
        $order = 'id desc';
        $param = $this->_limit_page_where($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy($order)->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->table);
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        $param['order'] = $order;
        $param['total'] = $total;

        return [$data, $total, $param];

    }

    /**
     * 条件查询
     *
     * @param    object    $select    查询对象
     * @param    intval    $where    是否搜索
     * @return    intval
     */
    protected function _limit_page_where(&$select, $param)
    {

        // 条件搜索
        if ($param) {

            // 关键字 + 自定义字段搜索
            if (isset($param['keyword']) && $param['keyword'] != '') {

                if ($param['id']) {
                    $select->where('id', (int) $$param['id']);
                } elseif ($param['ids']) {
                    $select->whereIn('id', $param['ids']);
                }

                if (isset($param['catname']) && $param['catname']) {
                    $select->where('catid IN (select id from `' . $this->dbprefix('news_category') . '` where `name` like "%' . $param['catname'] . '%")');
                }

                if (isset($param['title'])) {
                    $select->like('title', urldecode($param['title']));
                }
            }
            // 时间搜索
            if (isset($param['sdate']) && $param['sdate']) {
                $select->where('addtime BETWEEN ' . max((int) strtotime($param['sdate'] . ' 00:00:00'), 1) . ' AND ' . ($param['edate'] ? (int) strtotime($param['edate'] . ' 23:59:59') : SITE_TIME));
            } elseif (isset($param['edate']) && $param['edate']) {
                $select->where('addtime BETWEEN 1 AND ' . (int) strtotime($param['edate'] . ' 23:59:59'));
            }
            // 栏目查询
            // if (isset($param['catid']) && $param['catid']) {
            //     $cat['child'] ? $select->whereIn('catid', explode(',', $cat['childids'])) : $select->where('catid', (int)$param['catid']);
            // }
        }
        return $param;
    }

    public function setdisplayorder($id, $displayorder)
    {
        return $this->displayorder($this->table, $id, $displayorder);
    }

    //某分类的数据
    public function getList($catid = 0, $page = 1, $limit = 10)
    {
        $catid = isset($catid) ? intval($catid) : 0;
        $limit = isset($limit) ? intval($limit) : 10;
        $page = max(1, intval($page));
        if ($catid) {
            $query = $this->db->table($this->table)->where('catid', $catid);
        } else {
            $query = $this->db->table($this->table);
        }
        $data = $query->limit($limit, $limit * ($page - 1))->where('status', 1)->get()->getResultArray();
        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['thumb']) {
                    $att = $this->db->table('attachment')->where('id', intval($v['thumb']))->get()->getRowArray();
                    $data[$k]['thumb_url'] = isset($att) ? thumb($att['attachment'], 320, 320) : '';
                }
                $data[$k]['inputtime_date'] = date('Y-m-d H:i', $v['inputtime']);
                $data[$k]['updatetime_date'] = date('Y-m-d H:i', $v['updatetime']);
            }
        }
        return $data;
    }

    //=======category========

    //所有分类
    public function getAllCats()
    {
        $data = $this->db->table($this->table . '_cat')->select('id,pid,name,dirname,thumb')->where('show', 1)->orderBy('displayorder', 'ASC')->get()->getResultArray();
        if (!$data) {
            $data = [];
        } else {
            foreach ($data as $k => $v) {
                if ($v['thumb']) {
                    $att = $this->db->table('attachment')->where('id', intval($v['thumb']))->get()->getRowArray();
                    $data[$k]['thumb_url'] = isset($att) ? ams_thumb($att['attachment']) : '';
                }
            }
        }
        return $data;
    }

    public function cat_get($id)
    {
        $data = $this->db->table($this->table . '_cat')->where('id', $id)->get()->getRowArray();
        if ($data['thumb']) {
            $data['thumb_info'] = $this->db->table('attachment')->select('filename,attachment')->where('id', intval($data['thumb']))->get()->getRowArray();
        }
        return $data;
    }

    public function getCatTreeData()
    {
        $data = $_data = [];
        $data = $this->db->table($this->table . '_cat')->select('id,pid,child,name,status,dirname,enname,letter')->orderBy('displayorder', 'asc')->orderBy('id', 'asc')->get()->getResultArray();
        $tree = new \App\Libraries\Tree();
        $data = $tree->get($data);
        if ($data) {
            foreach ($data as $k => $v) {
                $_data[$v['id']] = $v;
            }
        }
        return $_data;
    }

    public function cat_add($data = [])
    {
        if (!$data || !$data['name']) {
            return mok_rt(1, '分类名称必须填写');
        } elseif (!$data['enname']) {
            return mok_rt(1, '英文名称必须填写');
        } elseif (!ctype_alnum($data['enname'])) {
            $enname = str_replace([' ', '-', '_'], '', $data['enname']);
            if (!ctype_alnum($enname)) {
                return mok_rt(1, '英文名称不规范');
            }
        } elseif ($this->field_exitsts($this->table . '_cat', 'name', $data['name'])) {
            return mok_rt(1, '分类已经存在了');
        } elseif ($this->field_exitsts($this->table . '_cat', 'enname', $data['enname'])) {
            return mok_rt(1, '分类英文名称已经存在了');
        }

        $insert = [
            'pid' => isset($data['pid']) ? (int) $data['pid'] : 0,
            'pids' => '',
            'name' => trim($data['name']),
            'enname' => str_replace(['/', '-', '_'], '', trim($data['enname'])),
            'letter' => '',
            'dirname' => str_replace(['/', '-', '_'], '', trim($data['enname'])),
            'child' => 0,
            'childids' => '',
            'icon' => isset($data['icon']) ? $data['icon'] : '',
            'show' => isset($data['show']) ? (int) $data['show'] : 0,
            'displayorder' => 0,
            'thumb' => isset($data['thumb']) ? intval($data['thumb']) : 0,
            'description' => isset($data['description']) ? $data['description'] : '',
        ];
        $this->db->table($this->table . '_cat')->insert($insert);
        $id = $this->db->insertID();

        if ($id) {
            //附件归属
            if (isset($data['thumb']) && $data['thumb']) {
                $related = $this->table . '_cat-' . $id;
                $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
            }
        }

        $this->cat_repair();
        return mok_rt(0, '操作成功', $id);
    }

    public function cat_edit($id = 0, $data = [])
    {
        if (!$data || !$data['name']) {
            return mok_rt(1, '分类名称必须填写');
        } elseif (!$id) {
            return mok_rt(1, '参数不全');
        } elseif (!$data['enname']) {
            return mok_rt(1, '英文名称必须填写');
        } elseif (!ctype_alnum($data['enname'])) {
            $enname = str_replace([' ', '-', '_'], '', $data['enname']);
            if (!ctype_alnum($enname)) {
                return mok_rt(1, '英文名称不规范');
            }
        } elseif ($this->field_exitsts($this->table . '_cat', 'name', $data['name'], $id)) {
            return mok_rt(1, '分类已经存在了');
        } elseif ($this->field_exitsts($this->table . '_cat', 'enname', $data['enname'], $id)) {
            return mok_rt(1, '分类英文名称已经存在了');
        }

        $update = [
            'pid' => isset($data['pid']) ? (int) $data['pid'] : 0,
            'name' => trim($data['name']),
            'icon' => isset($data['icon']) ? $data['icon'] : '',
            'enname' => str_replace(['/', '-', '_'], '', trim($data['enname'])),
            'dirname' => str_replace(['/', '-', '_'], '', trim($data['enname'])),
            'show' => isset($data['show']) ? (int) $data['show'] : 0,
            'thumb' => isset($data['thumb']) ? intval($data['thumb']) : 0,
            'description' => isset($data['description']) ? $data['description'] : '',
        ];

        $this->db->table($this->table . '_cat')->where('id', (int) $id)->update($update);

        //附件归属
        if (isset($data['thumb']) && $data['thumb']) {
            $related = $this->table . '_cat-' . $id;
            $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
        }

        $this->cat_repair();
        return mok_rt(0, '操作成功', $id);
    }

    public function cat_del($id)
    {
        if (!$id) {
            return mok_rt(1, '参数错误');
        }
        $row = $this->db->table($this->table . '_cat')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return mok_rt(1, '数据不存在', []);
        }
        $flag = $this->db->table($this->table . '_cat')->where('id', $id)->delete();
        if ($flag && $row['child'] && $row['childids']) {
            $arr = explode(',', $row['childids']);
            $this->db->table($this->table . '_cat')->whereIn('id', $arr)->delete();
        }
        if ($flag) {
            return mok_rt(0, 'OK');
        }
        return mok_rt(1, '操作失败');
    }

    private function cat_get_categorys($data = [])
    {
        if (is_array($data) && !empty($data)) {
            foreach ($data as $catid => $c) {
                $this->categorys[$catid] = $c;
                $result = [];
                foreach ($this->categorys as $_k => $_v) {
                    $_v['pid'] && $result[] = $_v;
                }
            }
        }
        return true;
    }

    private function cat_get_pids($catid, $pids = '', $n = 1)
    {
        if ($n > 6 || !is_array($this->categorys) || !isset($this->categorys[$catid])) {
            return false;
        }
        $pid = $this->categorys[$catid]['pid'];
        $pids = $pids ? $pid . ',' . $pids : $pid;
        if ($pid) {
            $pids = $this->cat_get_pids($pid, $pids, ++$n);
        } else {
            $this->categorys[$catid]['pids'] = $pids;
        }
        return $pids;
    }

    private function cat_get_childids($catid, $n = 1)
    {
        $childids = $catid;
        if ($n > 6 || !is_array($this->categorys) || !isset($this->categorys[$catid])) {
            return $childids;
        }
        if (is_array($this->categorys)) {
            foreach ($this->categorys as $id => $cat) {
                if ($cat['pid'] && $id != $catid && $cat['pid'] == $catid) {
                    $childids .= ',' . $this->cat_get_childids($id, ++$n);
                }
            }
        }
        return $childids;
    }

    public function cat_get_pdirname($catid)
    {
        if ($this->categorys[$catid]['pid'] == 0) {
            return '';
        }
        $t = $this->categorys[$catid];
        $pids = $t['pids'];
        $pids = explode(',', $pids);
        $catdirs = [];
        krsort($pids);
        foreach ($pids as $id) {
            if ($id == 0) {
                continue;
            }
            $catdirs[] = $this->categorys[$id]['dirname'];
            if ($this->categorys[$id]['pdirname'] == '') {
                break;
            }
        }
        krsort($catdirs);
        return implode('/', $catdirs) . '/';
    }

    public function cat_get_data()
    {
        $data = [];
        $_data = $this->db->table($this->table . '_cat')->orderBy('displayorder ASC,id ASC')->get()->getResultArray();
        if (!$_data) {
            return $data;
        }
        foreach ($_data as $t) {
            $data[$t['id']] = $t;
        }
        return $data;
    }

    public function cat_repair()
    {
        $this->categorys = $categorys = [];
        $this->categorys = $categorys = $this->cat_get_data();
        $this->cat_get_categorys($categorys);

        if (is_array($this->categorys)) {
            foreach ($this->categorys as $catid => $cat) {
                $pids = $this->cat_get_pids($catid);
                $childids = $this->cat_get_childids($catid);
                $child = is_numeric($childids) ? 0 : 1;
                $this->categorys[$catid]['pids'] = $pids;
                $this->categorys[$catid]['child'] = $child;
                $this->categorys[$catid]['childids'] = $childids;

                if ($categorys[$catid]['pids'] != $pids
                    || $categorys[$catid]['childids'] != $childids
                    || $categorys[$catid]['child'] != $child) {
                    $this->db->table($this->table . '_cat')->where('id', $catid)->update([
                        'pids' => $pids,
                        'child' => $child,
                        'childids' => $childids,
                    ]);
                }
            }
        }
    }

    public function cat_cache()
    {
        $cache = [];
        $category = $this->db->table($this->table . '_cat')->orderBy('displayorder ASC, id ASC')->get()->getResultArray();
        if ($category) {
            $CAT = $CAT_DIR = $level = [];
            foreach ($category as $c) {
                $pid = explode(',', $c['pids']);
                $level[] = substr_count($c['pids'], ',');
                $c['topid'] = isset($pid[1]) ? $pid[1] : $c['id'];
                $c['catids'] = explode(',', $c['childids']);
                $CAT[$c['id']] = $c;
                $CAT_DIR[$c['dirname']] = $c['id'];
            }
            $cache['category'] = $CAT;
            $cache['category_dir'] = $CAT_DIR;
        } else {
            $cache['category'] = [];
            $cache['category_dir'] = [];
        }
        $this->dcache->set('category', $cache['category']);
        $this->dcache->set('category-dir', $cache['category_dir']);
    }

}
